<template>
  <div class="filter-section">
    <span class="filter-label clickable-label" @click="openTypeListDialog">票据类型</span>
    <div class="tag-container">
      <span
        v-for="tag in ticketTypeTags"
        :key="tag.value"
        class="text-tag"
        :class="{ active: tag.type === 'primary' }"
        @click="handleTypeTagClick(tag)"
      >
        <span class="text-tag-label">{{ tag.label }}</span>
        <span class="text-tag-close" @click.stop="handleTypeClose(tag)">×</span>
      </span>

      <el-input
        v-if="typeInputVisible"
        v-model="typeInputValue"
        class="tag-input"
        size="large"
        @keyup.enter="handleTypeInputConfirm"
        @blur="handleTypeInputConfirm"
      />
      <el-button v-else class="button-new-tag" size="large" @click="showTypeInput"> + 新增类型 </el-button>
    </div>

    <!-- 银行列表弹窗组件 -->
    <BankListDialog ref="bankListDialogRef" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue"
import { ElMessage } from "element-plus"
import { getBankTypeDictAllListApi, createBankTypeDictApi } from "../../../../../api/calculator/index"
import BankListDialog from "../BankListDialog.vue"
import type { TagItem, BankTypeItem } from "./types"

// Emits
const emit = defineEmits<{
  "update:modelValue": [value: TagItem[]]
  change: [selectedTypes: TagItem[]]
  typeSelect: [tag: TagItem]
}>()

// 票据类型标签数据
const ticketTypeTags = ref<TagItem[]>([])

// 输入框状态
const typeInputVisible = ref<boolean>(false)
const typeInputValue = ref<string>("")

// 银行列表弹窗组件引用
const bankListDialogRef = ref<InstanceType<typeof BankListDialog> | null>(null)

// 处理票据类型标签点击
const handleTypeTagClick = async (tag: TagItem) => {
  // 单选模式：先清除所有标签的选中状态
  ticketTypeTags.value.forEach((t) => {
    t.type = ""
  })

  // 然后选中当前点击的标签
  tag.type = "primary"

  // 更新v-model
  emit("update:modelValue", ticketTypeTags.value)

  // 触发选中事件
  emit("typeSelect", tag)

  // 触发变化事件
  const selectedTypes = ticketTypeTags.value.filter((t) => t.type === "primary")
  emit("change", selectedTypes)
}

// 删除票据类型标签
const handleTypeClose = (tag: TagItem) => {
  const index = ticketTypeTags.value.indexOf(tag)
  if (index > -1) {
    ticketTypeTags.value.splice(index, 1)
    emit("update:modelValue", ticketTypeTags.value)

    const selectedTypes = ticketTypeTags.value.filter((t) => t.type === "primary")
    emit("change", selectedTypes)
  }
}

// 显示票据类型输入框
const showTypeInput = () => {
  typeInputVisible.value = true
  typeInputValue.value = ""
}

// 确认票据类型输入
const handleTypeInputConfirm = async () => {
  const typeName = typeInputValue.value.trim()
  if (!typeName) {
    typeInputVisible.value = false
    typeInputValue.value = ""
    return
  }

  try {
    // 调用API创建新的银行类型
    await createBankTypeDictApi({ type_name: typeName })

    ElMessage.success("新增类型成功")

    // 重新加载银行类型数据以保持同步
    await loadBankTypes()
  } catch (error) {
    console.error("创建银行类型失败:", error)
    ElMessage.error("新增类型失败")
  }

  typeInputVisible.value = false
  typeInputValue.value = ""
}

// 打开银行列表弹窗
const openTypeListDialog = () => {
  // 获取当前选中的类型，传递单个对象
  const selectedType = ticketTypeTags.value.find((t) => t.type === "primary")

  if (selectedType) {
    const typeData = {
      id: selectedType.value, // 票据类型ID，字符串格式如"3"
      label: selectedType.label, // 票据类型名称，如"国股"
      type: selectedType.type, // 选中状态，如"primary"
      value: selectedType.value // 票据类型ID值，如"3"
    }
    bankListDialogRef.value?.open(typeData)
  } else {
    bankListDialogRef.value?.open(undefined)
  }
}

// 获取银行类型数据
const loadBankTypes = async () => {
  try {
    const response = await getBankTypeDictAllListApi({})
    if (response.code === 200 && response.data?.data) {
      const bankTypes = response.data.data as BankTypeItem[]
      ticketTypeTags.value = bankTypes.map((item, index) => ({
        label: item.type_name,
        value: item.type_id.toString(),
        type: index === 0 ? "primary" : ""
      }))

      emit("update:modelValue", ticketTypeTags.value)

      // 如果有数据，触发变化事件
      if (ticketTypeTags.value.length > 0) {
        const selectedTypes = ticketTypeTags.value.filter((t) => t.type === "primary")
        emit("change", selectedTypes)
      }
    }
  } catch (error) {
    console.error("获取银行类型失败:", error)
    ElMessage.error("获取银行类型失败")
  }
}

// 暴露方法给父组件
defineExpose({
  loadBankTypes,
  getSelectedTypes: () => ticketTypeTags.value.filter((t) => t.type === "primary")
})

onMounted(async () => {
  // 加载银行类型数据
  await loadBankTypes()
})
</script>

<style scoped>
.filter-section {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.filter-label {
  font-weight: 500;
  color: #333;
  margin-right: 15px;
  min-width: 70px;
  font-size: 14px;
}

.clickable-label {
  cursor: pointer;
  transition: color 0.3s;
  position: relative;
}

.clickable-label:hover {
  color: #409eff;
}

.clickable-label:after {
  content: "📋";
  margin-left: 5px;
  font-size: 12px;
  opacity: 0.7;
}

.tag-container {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
  margin-right: 20px;
}

.tag-input {
  width: 90px;
}

.button-new-tag {
  border-style: dashed;
  color: #999;
}

.button-new-tag:hover {
  color: #409eff;
  border-color: #409eff;
}

/* 文本标签样式（替代 el-tag） */
.text-tag {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 4px 8px;
  border-radius: 4px;
  cursor: pointer;
  color: #666;
  border: 1px solid transparent;
  user-select: none;
}
.text-tag:hover {
  color: #409eff;
}
.text-tag.active {
  color: #409eff;
  font-weight: 500;
  border-color: rgba(64, 158, 255, 0.2);
  background-color: rgba(64, 158, 255, 0.05);
}
.text-tag-close {
  margin-left: 4px;
  color: #bbb;
  font-weight: bold;
  cursor: pointer;
}
.text-tag-close:hover {
  color: #f56c6c;
}
.text-tag-label {
  line-height: 1;
}
</style>
